<template>
  <view v-if="iv" class="container">
    <view class="title">登录/注册</view> <!-- 大标题靠左对齐 -->
    <view class="input-group">
      <view class="input-box">
        <input type="text" placeholder="请输入手机号" v-model="phoneNumber" />
      </view>
    </view>
    <view class="input-group half-width">
      <view class="input-box half-width-input">
        <input type="text" placeholder="请输入验证码" v-model="inputCaptcha" />
      </view>
      <button
        class="captcha-button half-width-captcha"
        :disabled="isCaptchaButtonDisabled"
        @click="sendCaptcha"
      >
        {{ isCaptchaButtonDisabled ? `重新发送(${countdown}s)` : "发送验证码" }}
      </button>
    </view>
    <button class="login-button" type="primary" @click="login">
      登录 / 注册
    </button>
    <view class="register-link">
      若未注册，将自动注册账号
    </view>
  </view>
</template>

<script>
// 引入 API
import { VerificationCodeAPI } from '../../services/api.js';  // 根据实际路径引入
import { OrderAPI } from '../../services/api.js'; // 引入 OrderAPI

export default {
  data() {
    return {
      phoneNumber: "", // 用户手机号
      inputCaptcha: "", // 用户输入的验证码
      captcha: "", // 后端生成的验证码（用于调试，实际应用可以不在前端存储）
      isCaptchaButtonDisabled: false, // 验证码按钮是否禁用
      countdown: 0, // 倒计时的秒数
      iv: false, // 页面是否可见
    };
  },
  methods: {
    // 发送验证码
    async sendCaptcha() {
      if (!this.phoneNumber) {
        uni.showToast({ title: "请输入手机号", icon: "none" });
        return;
      }

      try {
        // 调用后端 API 创建验证码
        const res = await VerificationCodeAPI.createCode(this.phoneNumber);
        console.log(res);
        if (res.message === "Verification code sent and saved successfully") {
          uni.showToast({
            title: `验证码已发送到手机号 ${this.phoneNumber}`,
            icon: "none",
          });
          this.startCountdown(60); // 开始 60 秒倒计时
        } else {
          uni.showToast({ title: res.data.message, icon: "none" });
        }
      } catch (error) {
        uni.showToast({
          title: "发送验证码失败，请稍后重试",
          icon: "none",
        });
        console.error("发送验证码失败", error);
      }
    },

    // 倒计时逻辑
    startCountdown(seconds) {
      this.countdown = seconds;
      this.isCaptchaButtonDisabled = true;

      const interval = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(interval);
          this.isCaptchaButtonDisabled = false;
        }
      }, 1000); // 每秒更新一次
    },

    // 登录并验证验证码
    async login() {
      if (!this.phoneNumber) {
        uni.showToast({ title: "请输入手机号", icon: "none" });
        return;
      }
      try {
        const res = await VerificationCodeAPI.verifyCode({
          phoneNumber: this.phoneNumber,
          code: this.inputCaptcha,
        });
        console.log(res.message);
        if (res.message === "Login successful") {
          const sessionValue = res.user.sessionValue;
          uni.setStorageSync("sessionValue", sessionValue);

          uni.showToast({ title: "登录成功", icon: "success" });
          uni.switchTab({
            url: "/pages/mainPage/pinMain",
          });
        } else {
          uni.showToast({ title: res.message, icon: "none" });
        }
      } catch (error) {
        uni.showToast({ title: "登录失败，请稍后重试", icon: "none" });
        console.error("登录错误:", error);
      }
    },
  },
  async mounted() {
    this.iv=await OrderAPI.fetchOrderData(); // 页面加载时获取订单数据并判断是否显示
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
  padding-top: 40px; /* 增加顶部留白 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start; /* 元素靠上排列 */
  height: 100vh;
  background-color: #f8f9fa; /* 浅灰背景 */
}

.title {
  font-size: 30px; /* 大标题字体大小 */
  font-weight: bold; /* 加粗 */
  color: #000; /* 黑色文字 */
  width: 100%; /* 占满宽度 */
  text-align: left; /* 靠左对齐 */
  margin-bottom: 30px; /* 与其他元素保持间距 */
}

.input-group {
  margin-bottom: 20px;
  width: 100%;
}

.input-box {
  display: flex;
  align-items: center;
  background-color: #fff;
  border: 2px solid #ec5f5f; /* 使用主题色 */
  border-radius: 32px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 18px;
  color: #333;
  background: none;
}

.half-width {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.half-width-input {
  width: 48%;
}

.captcha-button {
  width: 48%;
  background-color: #ec5f5f;
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  border: none;
  border-radius: 32px;
  text-align: center;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  cursor: pointer;
}

.captcha-button:disabled {
  background: #ccc;
  color: #666;
  cursor: not-allowed;
}

.captcha-button:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.login-button {
  width: 90%;
  background-color: #000;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  padding: 12px;
  border: none;
  border-radius: 32px;
  margin-top: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.register-link {
  margin-top: 15px;
  text-align: center;
  color: #666;
  font-size: 14px;
}
</style>
